package com.testingedu.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TestingeduFilter implements Filter {
	private static final Log log = LogFactory.getLog(TestingeduFilter.class);
	private static final List<String> ignoreURIs = new ArrayList<String>();//忽略的URL路径
	private ServletContext servletContext;
	public void destroy() {
	}

	public void doFilter(ServletRequest paramServletRequest,
			ServletResponse paramServletResponse, FilterChain paramFilterChain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) paramServletRequest;
		HttpServletResponse httpResponse = (HttpServletResponse)paramServletResponse;
		String[] uris = httpRequest.getRequestURI().split("/");
		if (uris != null && uris.length > 3) {
			if(ignoreURIs.contains(uris[2])) {	//忽略静态资源如images、css、js等文件夹下的资源
				paramFilterChain.doFilter(paramServletRequest, paramServletResponse);
			} else {	//处理servlet请求
				try {
					ActionInvoke actionInvoke = null;
					if ("admin".equals(uris[2])) { // 处理后台servlet
						actionInvoke = new AdminActionInvoke();
						//actionInvoke = ActionInvokePool.getAdminActionInvoke();
					} else { // 处理前台servlet
						actionInvoke = new FrontActionInvoke();
						//actionInvoke = ActionInvokePool.getFrontActionInvoke();
					}
					actionInvoke.request = httpRequest;
					actionInvoke.response = httpResponse;
					actionInvoke.servletContext = servletContext;
					actionInvoke.uris = uris;
					actionInvoke.invoke();
				} catch (Exception e) {
					log.error("程序运行错误："+e);
					httpRequest.getRequestDispatcher("/error/500.html").forward(httpRequest, httpResponse);
				}
			}
		} else {
			paramFilterChain	//交给tomcat处理，有可能404，也有可能进入index.jsp、contact.jsp
					.doFilter(paramServletRequest, paramServletResponse);
		}
	}

	public void init(FilterConfig paramFilterConfig) throws ServletException {
		String ignoreUrl = paramFilterConfig.getInitParameter("ignoreUrl");
		if (ignoreUrl != null) {
			for (String str : ignoreUrl.split(",")) {
				ignoreURIs.add(str.trim());
			}
		}
		this.setServletContext(paramFilterConfig.getServletContext());
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	public ServletContext getServletContext() {
		return servletContext;
	}
}
